#!/bin/bash

# 停止应用脚本
APP_NAME="yunji-news"
JAR_NAME="news-backend-1.0.0.jar"

echo "Stopping $APP_NAME..."

# 查找Java进程
PID=$(ps aux | grep $JAR_NAME | grep -v grep | awk '{print $2}')

if [ -z "$PID" ]; then
    echo "No $APP_NAME process found."
    exit 0
fi

echo "Found $APP_NAME process with PID: $PID"

# 优雅停止
kill $PID

# 等待进程停止
for i in {1..30}; do
    if ! ps -p $PID > /dev/null 2>&1; then
        echo "$APP_NAME stopped gracefully."
        exit 0
    fi
    echo "Waiting for $APP_NAME to stop... ($i/30)"
    sleep 1
done

# 强制停止
echo "Force stopping $APP_NAME..."
kill -9 $PID

if ! ps -p $PID > /dev/null 2>&1; then
    echo "$APP_NAME stopped forcefully."
else
    echo "Failed to stop $APP_NAME."
    exit 1
fi